<template>
  <div class="announcements-list">
    <el-card class="feedback-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">公告列表</span>
          <div class="header-controls">
            <el-input
              v-model="searchQuery"
              placeholder="搜索公告标题"
              style="width: 220px; margin-right: 15px;"
              clearable
              @input="debouncedSearch"
              @clear="handleSearchClear"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table
        :data="filteredAnnouncements"
        style="width: 100%"
        class="feedback-table"
        v-loading="loading"
      >
        <el-table-column prop="title" label="标题" min-width="200" />
        <el-table-column label="发布时间" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.create_at) }}
          </template>
        </el-table-column>
        <el-table-column label="发布人" width="120">
          <template #default="scope">
            {{ scope.row.publisher || `用户${scope.row.created_by_id}` }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.is_pinned" type="warning">置顶</el-tag>
            <el-tag v-else type="info">普通</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="scope">
            <el-button size="small" @click="viewDetail(scope.row)" class="operation-button">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
        />
      </div>
    </el-card>

    <!-- 公告详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="selectedAnnouncement?.title"
      width="600px"
      class="detail-dialog"
    >
      <div v-if="selectedAnnouncement" class="announcement-detail">
        <div class="meta-info">
          <span>发布时间: {{ formatDate(selectedAnnouncement.create_at) }}</span>
          <span>发布人: {{ selectedAnnouncement.publisher || `用户${selectedAnnouncement.created_by_id}` }}</span>
          <el-tag v-if="selectedAnnouncement.is_pinned" type="warning">置顶</el-tag>
        </div>
        <el-divider />
        <div class="content" v-html="selectedAnnouncement.content"></div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import requestUtil from '@/util/request.js'
import { ElMessage } from 'element-plus'
import debounce from 'lodash/debounce'

// 时间格式化函数
const formatDate = (dateStr) => {
  if (!dateStr) return ''

  // 解析日期字符串
  const date = new Date(dateStr)

  // 获取年、月、日
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  // 返回格式化后的字符串
  return `${year}-${month}-${day}`
}

// 公告数据
const announcements = ref([])
const loading = ref(false)

// 搜索和分页
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 用户信息缓存
const userCache = new Map()

// 获取用户信息
const fetchUserInfo = async (userId) => {
  // 如果缓存中有，直接返回
  if (userCache.has(userId)) {
    return userCache.get(userId)
  }

  try {
    const response = await requestUtil.get(`/user/secret/msg/${userId}`)
    const userData = response.data.data[0]
    const username = userData?.username || `用户${userId}`

    // 存入缓存
    userCache.set(userId, username)
    return username
  } catch (error) {
    console.error(`获取用户 ${userId} 信息失败:`, error)
    return `用户${userId}`
  }
}

// 获取所有公告数据（用于前端分页）
const fetchAllAnnouncements = async () => {
  loading.value = true
  try {
    const response = await requestUtil.get('/announcement/msg')

    if (response.data?.status === 200) {
      // 获取所有公告数据，确保是数组格式
      let rawData = response.data.data || []

      // 检查数据结构，如果是分页数据则提取列表
      if (Array.isArray(rawData)) {
        // 数据已经是数组格式
      } else if (rawData.list && Array.isArray(rawData.list)) {
        // 数据是分页格式，提取列表
        rawData = rawData.list
      } else {
        // 数据不是数组格式，创建空数组
        rawData = []
      }

      // 为每个公告添加发布者信息
      const processedData = await Promise.all(rawData.map(async (announcement) => {
        const publisher = await fetchUserInfo(announcement.created_by_id)
        return {
          ...announcement,
          create_at: announcement.create_at,
          publisher: publisher
        }
      }))

      // 保存所有数据
      allAnnouncements.value = processedData
      total.value = processedData.length
    } else {
      ElMessage.error(response.data?.message || '获取公告列表失败')
      allAnnouncements.value = []
      announcements.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error('获取公告列表失败: ' + (error.message || '未知错误'))
    console.error('获取公告列表失败:', error)
    allAnnouncements.value = []
    announcements.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 添加 allAnnouncements 用于存储所有数据
const allAnnouncements = ref([])

// 修改搜索相关逻辑 - 使用前端过滤
const filteredAnnouncements = computed(() => {
  // 确保数据是数组格式
  let filtered = Array.isArray(allAnnouncements.value) ? allAnnouncements.value : []

  // 应用搜索过滤
  if (searchQuery.value.trim()) {
    filtered = filtered.filter(announcement =>
      announcement.title?.includes(searchQuery.value.trim())
    )
  }

  // 更新总数量
  total.value = filtered.length

  // 应用分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

const debouncedSearch = debounce(() => {
  currentPage.value = 1 // 重置到第一页
}, 300)

// 分页相关
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 处理搜索清除
const handleSearchClear = () => {
  searchQuery.value = ''
  currentPage.value = 1
}

// 公告详情
const detailDialogVisible = ref(false)
const selectedAnnouncement = ref(null)

const viewDetail = (announcement) => {
  selectedAnnouncement.value = announcement
  detailDialogVisible.value = true
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAllAnnouncements()
})
</script>

<style scoped>
.announcements-list {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.feedback-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-controls {
  display: flex;
  align-items: center;
}

.feedback-table {
  margin-top: 20px;
}

.feedback-table :deep(.el-table__cell) {
  padding: 8px 0;
}

.feedback-table :deep(.el-table th) {
  font-weight: 600;
  background-color: #f5f7fa;
}

.operation-button {
  margin: 0 2px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.announcement-detail {
  padding: 20px;
}

.meta-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
  flex-wrap: wrap;
  gap: 10px;
}

.content {
  line-height: 1.6;
}

.content :deep(p) {
  margin: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 减少 ResizeObserver 错误的样式 */
:deep(.el-table) {
  min-height: 300px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .announcements-list {
    padding: 10px;
  }

  .feedback-table :deep(.el-table__cell) {
    padding: 5px 0;
  }

  .operation-button {
    margin: 2px 0;
  }
}
</style>
